<?php

use exceptions\ClassInterfaceNotImplementedException;
use exceptions\ClassNotFoundException;
use http\Middleware;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

if (!function_exists("abnormal")) {

    /**
     * 异常捕捉
     *
     * @param callable $callable
     * @param mixed|null $abnormal 异常返回
     * @return mixed
     */
    function abnormal(callable $callable, mixed $abnormal = null): mixed
    {
        try {
            return $callable();
        } catch (Throwable $e) {
            return is_callable($abnormal) ? $abnormal($e) : $abnormal;
        }
    }
}

if (!function_exists("instantiationClass")) {

    /**
     * 检测并实例化类
     *
     * @param string $className 类名
     * @param string|null $achieveInterface 是否实现某个接口
     * @param mixed $default
     * @return mixed
     */
    function instantiationClass(string $className, ?string $achieveInterface = null, mixed $default = null): mixed
    {
        if (!class_exists($className)) {
            return $default;
        }
        $class = new $className;
        if (!$achieveInterface) {
            goto end;
        }
        if (! $class instanceof $achieveInterface) {
            return $default;
        }
        end: return $class;
    }
}

if (!function_exists("httpClient")) {

    /**
     * http-client
     *
     * @param string|null $traceId
     * @return PendingRequest
     */
    function httpClient(?string $traceId = null): PendingRequest
    {
        $traceId = $traceId ?? Str::uuid()->toString();
        return Http::withoutVerifying()
            ->timeout(60)
            ->withUserAgent('admin-http-client.v1')
            ->withHeader('http-trade-id', $traceId)
            ->withMiddleware(Middleware::log(Log::channel('http-client'), $traceId));
    }
}






















